package com.ruoyi.management_controller.userinfo.interceptor;


import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName: AppJwtUtil
 * @Description:
 * @Author: TanXJ
 * @Date: 2022/9/2 18:01
 */
@Slf4j
@Component
public class JWTUtils {

    private static ServerTokenConfig serverTokenConfig;
    /**
     * 存进客户端的 token 的 key 名
     */
    public static final String USER_LOGIN_TOKEN = "token";

    @Autowired
    public void init(ServerTokenConfig serverTokenConfig) {
        JWTUtils.serverTokenConfig = serverTokenConfig;
    }

    /**
     * 生成token
     * @Param map payload信息
     * @Return token
     * */
    public static String getToken(Map<String, String> map){
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE, Math.toIntExact(serverTokenConfig.getTime()));
        //创建JWT构造器
        JWTCreator.Builder builder = JWT.create();
        // header默认的，不需要设置
        //设置payload
        builder.withExpiresAt(calendar.getTime());
        //遍历添加payload
        map.forEach((k,v)->{
            builder.withClaim(k,v);
        });
        //设置签名
        String token = builder.sign(Algorithm.HMAC256(serverTokenConfig.getKey()));
        return token;

    }
    /**
     * 验证JWT
     * @Param token
     * @Return DecodedJWT   验证通过，返回有效值，验证不通过，返回null
     * */
    public static DecodedJWT verify(String token){
        try{
            DecodedJWT jwtToken = JWT.require(Algorithm.HMAC256(serverTokenConfig.getKey())).build().verify(token);
            log.info("token验证成功 - " + jwtToken);
            return jwtToken;
        }catch(Exception e){
            log.error("token验证失败！");
            return null;
        }
    }


    /**
     * 获取JWT的payload信息
     * 可不写这个方法,由verify()完成了功能
     * */
    public static DecodedJWT getTokenInfo(String token){
        return JWT.require(Algorithm.HMAC256(serverTokenConfig.getKey())).build().verify(token);
    }

    //测试
    public static void main(String[] args) {
        Map<String,String> map = new HashMap<>();
        map.put("username","zhangsan");
        map.put("userId","12345");
        String token = JWTUtils.getToken(map);
        DecodedJWT jwtToken = JWTUtils.verify(token);
        System.out.println(jwtToken.getClaim("username").asString());
        System.out.println(jwtToken.getClaim("userId").asString());
    }


}
